import { Tree, Input, Card, Col, Row, Button, Tooltip, Popconfirm, message, Icon } from 'antd';
import Styles from './index.less';
import RightForm from './Form';
import { findAll, findOne,Delete } from '../../../api/user/menu';

const { TreeNode } = Tree;
const Search = Input.Search;

const x = 3;
const y = 2;
const z = 1;
const gData = [];

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || '0';
  const tns = _tns || gData;

  const children = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

const dataList = [];
const generateList = data => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: key });
    if (node.children) {
      generateList(node.children, node.key);
    }
  }
};
generateList(gData);
console.log(gData);
// console.log(dataList);
const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

export default class SearchTree extends React.Component {
  state = {
    expandedKeys: [],
    searchValue: '',
    autoExpandParent: true,
    ButtonStatus: 0, //0是添加。1是修改
    status: 0,
    findAllTree: [], //树形结构s数据
    findOneTree: '', //单条数据
    ClickTree: 0, //是否点击属性结构
    SelectId:'',  //点击树节点id
  };
  componentWillMount() {
    this.findAllTree();
  }

  /**
   * 树形结构数据
   */
  findAllTree = () => {
    //查询所有数据
    findAll().then(res => {
      console.log(res);
      if (res && res.code === 0) {
        this.setState({
          findAllTree: res.data,
        });
      }
    });
  };
  _getFindTree = id => {
    //查询单条数据
    return new Promise((resolve, reject) => {
      findOne(id)
        .then(res => {
          if (res && res.code === 0) {
            return resolve(res.data);
          }
        })
        .catch(err => {
          reject(err);
        });
    });
  };
  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  onChange = e => {
    const value = e.target.value;
    const expandedKeys = dataList
      .map(item => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, gData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  };
  addButton = () => {
      this.setState({
        ButtonStatus: 1,
        status: 0,
      });
  };
  editButton = () => {
    if (this.state.ClickTree) {
      this.setState({
        ButtonStatus: 1,
        status: 1,
      });
    } else {
      message.info('请选择修改节点');
    }
  };
  onSelect = (selectedKeys, e) => {
    //点击树节点
    console.log(selectedKeys);
    this._getFindTree(selectedKeys).then(res => {
      this.setState({
        ButtonStatus: 0,
        status: 0,
        findOneTree: res,
        ClickTree: 1,
        SelectId:selectedKeys,
      });
    });
  };
  _Delete = ()=>{
    Delete(this.state.SelectId).then(res=>{
      let result = JSON.parse(res);
      if(result&&result.data.affectedRows===1){
        message.success('删除成功');
        this.findAllTree();
      }else{
        message.error('删除失败');
      }
    })
  }
  render() {
    const { searchValue, expandedKeys, autoExpandParent } = this.state;
    const loop = data =>
      data.map((item, inde, data) => {
        const index = item.name.indexOf(searchValue);
        const beforeStr = item.name.substr(0, index);
        const afterStr = item.name.substr(index + searchValue.length);
        const title =
          index > -1 ? (
            <span key={inde}>
              {beforeStr}
              <span style={{ color: '#f50' }}>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{item.name}</span>
          );
        if (item.routes) {
          return (
            <TreeNode key={item.id} title={title}>
              {loop(item.routes)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.id} title={title} />;
      });
    return (
      <div>
        <Row gutter={10}>
          <Col span={8}>
            <Card
              title="菜单"
              bordered={false}
              extra={
                <div>
                  <Tooltip placement="topLeft" title="添加">
                    <Button
                      style={{ marginRight: 10 }}
                      icon="plus"
                      type="primary"
                      shape="circle"
                      size="small"
                      onClick={() => this.addButton()}
                    />
                  </Tooltip>
                  <Tooltip placement="topLeft" title="修改">
                    <Button
                      style={{ marginRight: 10 }}
                      icon="form"
                      type="dashed"
                      shape="circle"
                      size="small"
                      onClick={() => this.editButton()}
                    />
                  </Tooltip>
                  <Popconfirm
                    title="确定删除"
                    onCancel={() => {
                      message.info('取消');
                    }}
                    onConfirm={() => {
                      if (this.state.ClickTree) {
                        this._Delete();
                        console.log(this.state.ClickTree);
                      } else {
                        message.info('请选择删除节点');
                      }
                    }}
                    icon={<Icon type="question-circle-o" />}
                    style={{ color: 'red' }}
                  >
                    <Button
                      style={{ marginRight: 10 }}
                      icon="delete"
                      type="danger"
                      shape="circle"
                      size="small"
                    />
                  </Popconfirm>
                </div>
              }
            >
              <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={this.onChange} />
              <Tree
                onSelect={this.onSelect}
                onExpand={this.onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
              >
                {loop(this.state.findAllTree)}
              </Tree>
            </Card>
          </Col>
          <Col span={16}>
            <Card bordered={false}>
              <RightForm
                ref="ShowButton"
                status={this.state.status}
                ButtonStatus={this.state.ButtonStatus}
                findOneTree={this.state.findOneTree}
                FindAll={this.findAllTree}
              />
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}
